import { platformSubmitAuth, checkSession, createSession } from '../api/index.js'

const getCheckSessionStatus = async () => {
  let status = null,
    checkFun = () => {
      return new Promise((resolve, reject) => {
        wx.checkSession({
          success: res => resolve(res),
          fail: res => reject(res)
        })
      })
    }

  await checkFun()
    .then(res => (status = true))
    .catch(res => (status = false))
  console.log('get wx CheckSession Status', status)
  return status
}

const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        let { code } = res
        if (!code) {
          wx.showToast({
            title: '微信登录失败',
            icon: 'none',
            duration: 2000
          })
          reject(res)
          return
        }
        resolve(res)
      },
      fail: res => {
        wx.showToast({
          title: '微信登录失败',
          icon: 'none',
          duration: 2000
        })
        reject(res)
      }
    })
  })
}

const submitAuth = ({ code = '', encryptData = '', encryptIv = '' } = {}) => {
  if (code === '') return console.log('The lack of wx code')

  let isAuth = wx.getStorageSync('AUTH_TAG')
  if (!isAuth) {
    return wx
      .$request(platformSubmitAuth, {
        method: 'POST',
        data: {
          code,
          encryptData,
          encryptIv
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      })
      .then(
        ({
          data: { sidName, sidValue, userId, platformUserId, platformAccountId }
        }) => {
          wx.setStorageSync('LOGIN_COOKIE_KEY', sidName)
          wx.setStorageSync('LOGIN_COOKIE', sidValue)
          wx.setStorageSync('AUTH_TAG', true)
          wx.$getGlobalData().userId = userId
          wx.$getGlobalData().openId = platformUserId
          wx.$getGlobalData().platformAccountId = platformAccountId
          return Promise.resolve()
        }
      )
      .catch(data => {
        return Promise.reject(data)
      })
  }
  return Promise.resolve()
}

const platformCheckSession = () => {
  return wx
    .$request(checkSession)
    .then(({ data }) => {
      return Promise.resolve(data)
    })
    .catch(() => {
      return Promise.resolve(null)
    })
}

// 获取已授权用户信息
const getAuthInfo = () => {
  if (wx.$getGlobalData().openId && wx.$getGlobalData().userId) {
    wx.setStorageSync('HAS_GET_ACCOUNTINFO', true)
    return Promise.resolve()
  } else {
    return wx
      .$request(createSession, {
        data: {
          code: wx.$getGlobalData().code
        }
      })
      .then(
        ({ data: { sidName, sidValue, userId, platformUserId, platformAccountId, platformUserHeadImg, platformUserName } }) => {
          wx.setStorageSync('LOGIN_COOKIE_KEY', sidName)
          wx.setStorageSync('LOGIN_COOKIE', sidValue)
          wx.$getGlobalData().userId = userId
          wx.$getGlobalData().openId = platformUserId
          wx.$getGlobalData().platformAccountId = platformAccountId
          wx.$getGlobalData().userInfo = {
            avatarUrl: platformUserHeadImg,
            nickName: platformUserName
          }
          // 重新获取code防止重复使用
          wxLogin().then(response => {
            wx.$getGlobalData().code = response.code
            console.info('getAuthUserInfo get code:', response.code)
          })
          wx.setStorageSync('HAS_GET_ACCOUNTINFO', true)
          return Promise.resolve()
        },
        ({ data }) => {
          // 重新获取code防止重复使用
          wxLogin().then(response => {
            wx.$getGlobalData().code = response.code
            console.info('getAuthUserInfo get code:', response.code)
          })
          wx.setStorageSync('HAS_GET_ACCOUNTINFO', true)
          return Promise.resolve()
        }
      )
  }
}

export {
  getCheckSessionStatus,
  wxLogin,
  submitAuth,
  platformCheckSession,
  getAuthInfo
}
